<?php

namespace App\Services\Home;

use App\Models\Community;
use App\Traits\CommonData;
use Illuminate\Support\Facades\DB;

class CommunityService
{
    use CommonData;

    protected $regionService;

    public function __construct(RegionService $regionService)
    {
        $this->regionService = $regionService;
    }

    public function getSingle($id)
    {
        return Community::findOrFail($id);
    }
    public function getDetailById($id)
    {
        return Community::withCount(['handroom','rentalhouse','handroom as handroom_avg' =>function($query){
            $query->select(DB::raw("avg(average) as avg_price"));
        }])->findOrFail($id);
    }

    /**
     * @param $request
     * @return \Illuminate\Http\JsonResponse
     * 小区数据
     */
    public function data($request)
    {
        $model = Community::query();
        if($request->input('keyword')){
            $model = $model->where('title','like','%'.$request->input('keyword').'%');
        }
        if ($request->input('town')){
            $model = $model->whereIn('town_id',$request->input('town'));
        }else{
            if ($request->input('area') && $request->input('area') != 0){
                $ids = $this->regionService->getIds($request->input('area'));
                $model = $model->whereIn('area',$ids);
            }
            if ($request->input('station')){
                $model = $model->whereIn('metro_station_id',$request->input('station'));
            }else{
                if($request->input('metro_id') > 0){
                    $model = $model->where('metro_id',$request->input('metro_id'));
                }
            }
        }

        if ($request->input('min_price')>=0 && $request->input('max_price')>0){
            $model = $model->whereBetween('price',[$request->input('min_price'),$request->input('max_price')]);
        }

        if ($request['year']) {
            $age = explode(',', $request->input('year'));
            $min = date('Y') - $age[1];
            $max = date('Y') - $age[0];
            $model = $model->whereBetween('year', [$min, $max]);
        }
        if($request->input('sort') == 'default'){
            $model = $model->orderBy('created_at','desc');
        }elseif($request->input('sort') == 'asc'){
            $model = $model->orderBy('price','asc');
        }elseif($request->input('sort') == 'desc'){
            $model = $model->orderBy('price','desc');
        }elseif($request->input('sort') == 'popular'){
            $model = $model->orderBy('follow','desc');
        }
        $res = $model->withCount(['handroom','rentalhouse','handroom as handroom_avg' =>function($query){
            $query->select(DB::raw("avg(average) as avg_price"));
        }])->with('attribute')->paginate($request->input('pagesize',10));

        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'total' => $res['total'],
            'data'  => $res
        ];
        return response()->json($data);
    }

    /**
     * @param $id
     * 附近的小区
     * 2000 表示查询两公里内的小区
     */
    public function getNearbyCommunityById($id)
    {
        $data = Community::findOrFail($id);
        $lat_lng = $this->calcScope($data->latitude,$data->longitude,2000);
        $res = Community::latest()->withCount(['handroom','handroom as handroom_avg' =>function($query){
            $query->select(DB::raw("avg(average) as avg_price"));
        }])->where('id','<>',$id)->where('latitude','>',$lat_lng['minLat'])->where('latitude','<',$lat_lng['maxLat'])
            ->where('longitude','>',$lat_lng['minLng'])->where('longitude','<',$lat_lng['maxLng'])->take(5)->get();
        return $res;
    }
}